{{- define "falco_resources" }}
cpu: 10m
memory: 25Mi
{{- end }}

{{- define "falcosidekick_resources" }}
cpu: 5m
memory: 10Mi
{{- end }}

{{- define "falco_rules_loader" }}
cpu: 10m
memory: 25Mi
{{- end }}

{{- if (.Values.global.enabledModules | has "vertical-pod-autoscaler-crd") }}
---
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: {{ $.Chart.Name }}
  namespace: d8-{{ $.Chart.Name }}
  {{- include "helm_lib_module_labels" (list . (dict "app" $.Chart.Name "workload-resource-policy.deckhouse.io" "every-node")) | nindent 2 }}
spec:
  targetRef:
    apiVersion: apps/v1
    kind: DaemonSet
    name: {{ $.Chart.Name }}
  updatePolicy:
    updateMode: "Auto"
  resourcePolicy:
    containerPolicies:
    - containerName: "falco"
      minAllowed:
      {{- include "falco_resources" . | nindent 8 }}
      maxAllowed:
        cpu: 4000m
        memory: 5Gi
    - containerName: "falcosidekick"
      minAllowed:
      {{- include "falcosidekick_resources" . | nindent 8 }}
      maxAllowed:
        cpu: 100m
        memory: 300Mi
    - containerName: "rules-loader"
      minAllowed:
      {{- include "falco_rules_loader" . | nindent 8 }}
      maxAllowed:
        cpu: 100m
        memory: 300Mi
    {{- include "helm_lib_vpa_kube_rbac_proxy_resources" . | nindent 4 }}
{{- end }}
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: {{ $.Chart.Name }}
  namespace: d8-{{ $.Chart.Name }}
  {{- include "helm_lib_module_labels" (list . (dict "app" $.Chart.Name)) | nindent 2 }}
spec:
  selector:
    matchLabels:
      app: {{ $.Chart.Name }}
  minReadySeconds: 1
  updateStrategy:
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: {{ $.Chart.Name }}
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
    spec:
      imagePullSecrets:
      - name: deckhouse-registry
      serviceAccountName: {{ $.Chart.Name }}
      {{- include "helm_lib_tolerations" (tuple . "any-node") | nindent 6 }}
      {{- include "helm_lib_priority_class" (tuple . "cluster-medium") | nindent 6 }}
      {{- include "helm_lib_module_pod_security_context_run_as_user_root" . | nindent 6 }}
      hostNetwork: true
      dnsPolicy: ClusterFirstWithHostNet
      containers:

      - name: falco
        # TODO(nabokihms): Fix 'Error response from daemon: invalid CapAdd: unknown capability: "CAP_BPF"'
        # Migrate to capabilities: "BPF" "SYS_RESOURCE" "PERFMON" "SYS_PTRACE"
        {{- include "helm_lib_module_container_security_context_privileged_read_only_root_filesystem" . | nindent 8 }}
        image: {{ include "helm_lib_module_image" (list . "falco") }}
        args:
        - /usr/bin/falco
        - -K
        - /var/run/secrets/kubernetes.io/serviceaccount/token
        - -k
        - https://$(KUBERNETES_SERVICE_HOST)
        - --k8s-node
        - $(FALCO_K8S_NODE_NAME)
        - -pk
        - --modern-bpf
        - --unbuffered
        env:
        - name: FALCO_K8S_NODE_NAME
          valueFrom:
            fieldRef:
              fieldPath: spec.nodeName
        - name: SKIP_DRIVER_LOADER
          value: ""
        livenessProbe:
          failureThreshold: 3
          httpGet:
            path: /healthz
            port: 8765
            scheme: HTTP
          initialDelaySeconds: 60
          periodSeconds: 15
          successThreshold: 1
          timeoutSeconds: 5
        readinessProbe:
          failureThreshold: 3
          httpGet:
            path: /healthz
            port: 8765
            scheme: HTTP
          initialDelaySeconds: 30
          periodSeconds: 15
          successThreshold: 1
          timeoutSeconds: 5
        resources:
          requests:
            {{- include "helm_lib_module_ephemeral_storage_only_logs" . | nindent 14 }}
          {{- if not (.Values.global.enabledModules | has "vertical-pod-autoscaler-crd") }}
            {{- include "falco_resources" . | nindent 14 }}
          {{- end }}
        volumeMounts:
        - mountPath: /root/.falco
          name: root-falco-fs
        - mountPath: /host/proc
          name: proc-fs
        - mountPath: /host/dev
          name: dev-fs
          readOnly: true
        - mountPath: /etc/falco
          name: config-volume
        - mountPath: /sys/kernel/debug
          name: debug-fs
        - mountPath: /etc/falco/webhook
          name: webhook-tls
          readOnly: true
        - name: rules-data
          mountPath: /etc/falco/rules.d
        - name: containerdsock
          mountPath: /run/containerd/containerd.sock

      - name: falcosidekick
        {{- include "helm_lib_module_container_security_context_read_only_root_filesystem_capabilities_drop_all" . | nindent 8 }}
        image: {{ include "helm_lib_module_image" (list . "falcosidekick") }}
        env:
        - name: LISTENADDRESS
          value: "127.0.0.1"
        {{- if .Values.runtimeAuditEngine.debugLogging }}
        - name: DEBUG
          value: "true"
        {{- end }}
        livenessProbe:
          httpGet:
            path: /sidekick/ping
            port: 8766
            scheme: HTTPS
          initialDelaySeconds: 10
          periodSeconds: 5
        readinessProbe:
          httpGet:
            path: /sidekick/ping
            port: 8766
            scheme: HTTPS
          initialDelaySeconds: 10
          periodSeconds: 5
        resources:
          requests:
            {{- include "helm_lib_module_ephemeral_storage_only_logs" . | nindent 14 }}
          {{- if not (.Values.global.enabledModules | has "vertical-pod-autoscaler-crd") }}
            {{- include "falcosidekick_resources" . | nindent 14 }}
          {{- end }}

      - name: rules-loader
        {{- include "helm_lib_module_container_security_context_read_only_root_filesystem" . | nindent 8 }}
        image: {{ include "helm_lib_module_image" (list . "rulesLoader") }}
        env:
        - name: SHELL_OPERATOR_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: VALIDATING_WEBHOOK_CONFIGURATION_NAME
          value: d8-runtime-audit-engine.deckhouse.io
        - name: VALIDATING_WEBHOOK_SERVICE_NAME
          value: {{ .Chart.Name }}-webhook
        - name: DEBUG_UNIX_SOCKET
          value: /tmp/shell-operator-debug.socket
        resources:
          requests:
            {{- include "helm_lib_module_ephemeral_storage_only_logs" . | nindent 12 }}
{{- if not ( .Values.global.enabledModules | has "vertical-pod-autoscaler-crd") }}
            {{- include "falco_rules_loader" . | nindent 12 }}
{{- end }}
        volumeMounts:
        - mountPath: /validating-certs
          name: webhook-tls
        - name: rules-data
          mountPath: /etc/falco/rules.d
        - name: tmp
          mountPath: /tmp
        - mountPath: /etc/falco
          name: config-volume
        # Check that rules were uploaded successfully
        readinessProbe:
          exec:
            command:
            - cat
            - /tmp/ready
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 5

      - name: kube-rbac-proxy
        {{- include "helm_lib_module_container_security_context_read_only_root_filesystem_capabilities_drop_all" . | nindent 8 }}
        image: {{ include "helm_lib_module_common_image" (list . "kubeRbacProxy") }}
        args:
        - "--secure-listen-address=$(KUBE_RBAC_PROXY_LISTEN_ADDRESS):8766"
        - "--client-ca-file=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
        - "--v=2"
        - "--logtostderr=true"
        - "--stale-cache-interval=1h30m"
        - "--livez-path=/livez"
        env:
        - name: KUBE_RBAC_PROXY_LISTEN_ADDRESS
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: KUBE_RBAC_PROXY_CONFIG
          value: |
            excludePaths:
            - /sidekick/ping
            upstreams:
            - upstream: http://127.0.0.1:2801/
              path: /sidekick/
              authorization:
                resourceAttributes:
                  namespace: d8-{{ $.Chart.Name }}
                  apiGroup: apps
                  apiVersion: v1
                  resource: daemonsets
                  subresource: prometheus-metrics
                  name: {{ $.Chart.Name }}
        ports:
        - containerPort: 8766
          name: https-metrics
        livenessProbe:
          httpGet:
            path: /livez
            port: 8766
            scheme: HTTPS
        readinessProbe:
          httpGet:
            path: /livez
            port: 8766
            scheme: HTTPS
        resources:
          requests:
            {{- include "helm_lib_module_ephemeral_storage_only_logs" . | nindent 14 }}
          {{- if not (.Values.global.enabledModules | has "vertical-pod-autoscaler-crd") }}
            {{- include "helm_lib_container_kube_rbac_proxy_resources" . | nindent 14 }}
          {{- end }}

      terminationGracePeriodSeconds: 30
      volumes:
      - emptyDir: {}
        name: root-falco-fs
      - emptyDir: {}
        name: rules-data
      - emptyDir: {}
        name: tmp
      - hostPath:
          path: /boot
        name: boot-fs
      - hostPath:
          path: /lib/modules
        name: lib-modules
      - hostPath:
          path: /usr
        name: usr-fs
      - hostPath:
          path: /run/containerd/containerd.sock
        name: containerdsock
      - hostPath:
          path: /etc
        name: etc-fs
      - hostPath:
          path: /dev
        name: dev-fs
      - hostPath:
          path: /proc
        name: proc-fs
      - hostPath:
          path: /sys/kernel/debug
        name: debug-fs
      - name: config-volume
        configMap:
          defaultMode: 420
          name: {{ $.Chart.Name }}
          items:
          - key: falco.yaml
            path: falco.yaml
    {{- range $path, $_ := (.Files.Glob "rules/*") }}
          - key: {{ trimPrefix "rules/" $path }}
            path: {{ trimPrefix "rules/" $path }}
    {{- end }}
      - name: webhook-tls
        secret:
          secretName: runtime-audit-engine-webhook-tls
